package com.netposa.datawarehouse.bodysearch.web.rest;

import com.google.common.base.Strings;
import com.netposa.appwebres.WebResCallback;
import com.netposa.appwebres.common.WebResCriteria;
import com.netposa.appwebres.common.WebResInfo;
import com.netposa.appwebres.exception.WebResException;
import com.netposa.appwebres.extend.Checks;
import com.netposa.datawarehouse.bodysearch.client.DeviceServiceFeign;
import com.netposa.datawarehouse.bodysearch.convert.DictionaryConvert;
import com.netposa.datawarehouse.bodysearch.service.BodyService;
import com.netposa.datawarehouse.bodysearch.web.enums.DeviceAbilityEnum;
import com.netposa.datawarehouse.bodysearch.web.ext.PvmContextExt;
import com.netposa.datawarehouse.bodysearch.web.ext.PvmRole;
import com.netposa.datawarehouse.bodysearch.web.model.BodyCondition;
import com.netposa.datawarehouse.bodysearch.web.model.BodyDownloadCondition;
import com.netposa.datawarehouse.bodysearch.web.model.DeviceTreeCondition;
import com.netposa.datawarehouse.bodysearch.web.model.RecordIdsCondition;
import com.netposa.datawarehouse.bodysearch.web.vo.BodyVO;
import com.netposa.library.datawarehouse.aggregate.annotation.Aggregate;
import com.netposa.library.datawarehouse.aggregate.helper.ResourceDefined.ResourceType;
import com.netposa.npwonder.model.PvmUser;
import com.netposa.npwonder.utils.PvmContext;
import com.netposa.vias.client.UploadClient;
import com.netposa.vias.client.entity.ExportEntity;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"body"})
public class BodyController {
   private static final Logger log = LoggerFactory.getLogger(BodyController.class);
   @Autowired
   private BodyService bodyService;
   @Autowired
   private UploadClient uploadClient;
   @Autowired
   private PvmContext pvmContext;
   @Autowired
   @Qualifier("searchDictionaryConvert")
   private DictionaryConvert convert;
   private Integer ROLE_TYPE = 1;
   private String CODE_TYPE = "1";
   @Autowired
   private DeviceServiceFeign deviceServiceFeign;
   @Autowired
   private PvmContextExt pvmContextExt;

   private List<String> getDeviceIdByRoleId(HttpServletRequest request) {
      List<String> deviceIdList = new ArrayList<>();

      try {
         List<PvmRole> roleList = this.pvmContextExt.getRole(request);
         Iterator<PvmRole> var4 = roleList.iterator();

         while(var4.hasNext()) {
            PvmRole pvmRole = var4.next();
            log.info("权限标记" + pvmRole.getCode());
            if (pvmRole.getType() == this.ROLE_TYPE && this.CODE_TYPE.equals(pvmRole.getCode())) {
               DeviceTreeCondition deviceTreeCondition = new DeviceTreeCondition();
               List ablilists = new ArrayList();
               ablilists.add(DeviceAbilityEnum.BODY.getStringValue());
               deviceTreeCondition.setAbilities(ablilists);
               WebResInfo data = this.deviceServiceFeign.staypoint(deviceTreeCondition);
               if ("200".equals(data.getCode())) {
                  List<Map<String, String>> devices = (ArrayList)data.getData();
                  deviceIdList = (List)devices.stream().map((item) -> {
                     return (String)item.get("id");
                  }).collect(Collectors.toList());
               }

               return (List)deviceIdList;
            }
         }
      } catch (Exception var10) {
         log.error(var10.getMessage(), var10);
      }

      return (List)deviceIdList;
   }

   @PostMapping({"get_by_recordIds"})
   public WebResInfo getBodyByRecordIds(@RequestBody final RecordIdsCondition condition) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            Checks.checkNotEmpty(condition.getRecordIds());
            criteria.addSingleResult(BodyController.this.bodyService.getBodyOriginalByIds(condition));
         }
      }).sendRequest(new Object[0]);
   }

   @GetMapping({"get_body"})
   public WebResInfo getBodyById(@RequestParam(name = "recordId") final String recordId) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            Checks.checkNotEmpty(recordId);
            criteria.addSingleResult(BodyController.this.bodyService.getBodyByRecordId(recordId));
         }
      }).sendRequest(new Object[0]);
   }

   @GetMapping({"get_feature"})
   public WebResInfo getBodyFeatureById(@RequestParam(name = "recordId") final String recordId) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            Checks.checkNotEmpty(recordId);
            criteria.addSingleResult(BodyController.this.bodyService.getBodyFeatureById(recordId));
         }
      }).sendRequest(new Object[0]);
   }

   @GetMapping({"get_origin"})
   public WebResInfo getBodyOriginById(@RequestParam(name = "recordId") final String recordId) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            Checks.checkNotEmpty(recordId);
            criteria.addSingleResult(BodyController.this.bodyService.getBodyOriginById(recordId));
         }
      }).sendRequest(new Object[0]);
   }

   @GetMapping({"topx"})
   public WebResInfo topBody(@RequestParam(name = "count",required = false,defaultValue = "10") final Integer count, @RequestParam(name = "deviceId",required = false) final String deviceId, @RequestParam(name = "startTime",required = false) final Long startTime, @RequestParam(name = "endTime",required = false) final Long endTime) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            criteria.addSingleResult(BodyController.this.bodyService.topX(count, deviceId, startTime, endTime));
         }
      }).sendRequest(new Object[0]);
   }

   @PostMapping({"list"})
   @Aggregate(
      name = "list",
      type = ResourceType.BODY
   )
   public WebResInfo getBodyByParams(@RequestBody final BodyCondition bodyCondition, HttpServletRequest request) {
      if (StringUtils.isEmpty(bodyCondition.getDeviceId())) {
         List deviceIdList = this.getDeviceIdByRoleId(request);
         if (deviceIdList != null && deviceIdList.size() > 0) {
            log.error("设备数量：" + deviceIdList.size());
            String deviceIds = org.apache.commons.lang3.StringUtils.join(deviceIdList, ",");
            bodyCondition.setDeviceId(deviceIds);
         }
      }

      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            if (bodyCondition.getCurrentPage() >= 1 && bodyCondition.getPageSize() >= 1) {
               if (bodyCondition != null && !Strings.isNullOrEmpty(bodyCondition.getSources()) && !bodyCondition.getSources().matches("-?\\d+(,-?\\d+)*")) {
                  throw new WebResException("400", new Object[]{"sources format error."});
               } else {
                  criteria.addSingleResult(BodyController.this.bodyService.getBodyOriginByParams(bodyCondition));
               }
            } else {
               throw new WebResException("400");
            }
         }
      }).sendRequest(new Object[0]);
   }

   @PostMapping({"count"})
   @Aggregate(
      name = "count",
      type = ResourceType.BODY
   )
   public WebResInfo count(@RequestBody final BodyCondition condition) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            if (!StringUtils.isEmpty(condition.getDeviceId())) {
               condition.setDeviceId("('" + condition.getDeviceId().replace(",", "','") + "')");
            }

            if (condition != null && !Strings.isNullOrEmpty(condition.getSources()) && !condition.getSources().matches("-?\\d+(,-?\\d+)*")) {
               throw new WebResException("400", new Object[]{"sources format error."});
            } else {
               criteria.addSingleResult(BodyController.this.bodyService.explainComputeCount(condition));
            }
         }
      }).sendRequest(new Object[0]);
   }

   @PostMapping({"download"})
   public WebResInfo downloadExport(@RequestBody final BodyDownloadCondition condition, final HttpServletRequest request) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            if (condition.getCurrentPage() > 0 && condition.getPageSize() > 0) {
               List bodyVOList = BodyController.this.bodyService.downloadExport(condition);
               Collections.sort(bodyVOList, new Comparator<BodyVO>() {
                  public int compare(BodyVO o1, BodyVO o2) {
                     if (o1.getAbsTime() > o2.getAbsTime()) {
                        return -1;
                     } else {
                        return Objects.equals(o1.getAbsTime(), o2.getAbsTime()) ? 0 : 1;
                     }
                  }
               });
               PvmUser pvmUser = BodyController.this.pvmContext.getPvmUser(request);
               BodyController.log.info("pvmUser={}", pvmUser);
               if (pvmUser == null) {
                  BodyController.log.error("get PvmUser step error");
                  throw new WebResException("401");
               } else {
                  ExportEntity exportEntity = BodyController.this.wrapExportEntity(condition, pvmUser, bodyVOList);
                  WebResInfo webResInfo = BodyController.this.uploadClient.export(exportEntity);
                  if (webResInfo.getCode().equals("200")) {
                     criteria.addSingleResult(webResInfo.getData());
                  } else {
                     BodyController.log.error("uploadClient failed");
                     throw new WebResException(webResInfo.getCode());
                  }
               }
            } else {
               throw new WebResException("400");
            }
         }
      }).sendRequest(new Object[0]);
   }

   private ExportEntity wrapExportEntity(BodyDownloadCondition condition, PvmUser pvmUser, List bodyVOList) {
      ExportEntity exportEntity = new ExportEntity();
      exportEntity.setUserId(pvmUser.getId());
      exportEntity.setUserName(pvmUser.getName());
      String[] columnNames = new String[]{"通过时间", "抓拍地点", "性别", "上衣款式", "上身颜色", "下衣款式", "下身颜色", "图片地址", "随身物品", "设备类型", "头部标识"};
      exportEntity.setColumnNames(columnNames);
      String fileName;
      if (org.apache.commons.lang.StringUtils.isBlank(condition.getFileName())) {
         fileName = "人体数据信息_" + DateFormatUtils.format(new Date(), "yyyy-MM-dd-HH-mm-ss");
      } else {
         fileName = condition.getFileName();
      }

      exportEntity.setSheetName(fileName);
      List bodyStringList = new ArrayList();
      Iterator var8 = bodyVOList.iterator();

      while(var8.hasNext()) {
         BodyVO body = (BodyVO)var8.next();
         String[] row = this.convert.convert(body, condition);
         bodyStringList.add(row);
      }

      exportEntity.setDatas(bodyStringList);
      return exportEntity;
   }

   @GetMapping({"delete"})
   public WebResInfo deleteBodyByRecordIds(@RequestParam(name = "ids") final String ids) {
      return (new WebResCallback() {
         public void execute(WebResCriteria criteria, Object... params) {
            BodyController.this.bodyService.deleteBody(ids);
         }
      }).sendRequest(new Object[0]);
   }
}
